package service.impl;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
import dao.MallUserDao;
import dao.impl.MallUserDaoImpl;
import model.InnerResult;
import model.po.User;
import model.vo.UserSignVO;
import service.MallUserService;

import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.List;
import java.util.Random;

import static crypt.UserPwdFactor.FACTOR;

public class MallUserServiceImpl implements MallUserService {
    private MallUserDao mallUserDao = new MallUserDaoImpl();
    private static final Random RANDOM = new SecureRandom();

    private String getHashPwd(byte[] hashPwd) {
        StringBuilder sb = new StringBuilder(hashPwd.length);
        String tmp;
        for (byte b : hashPwd) {
            tmp = Integer.toHexString(0xFF & b);
            if (tmp.length() < 2) {
                sb.append(0);
            }
            sb.append(tmp.toUpperCase());
        }
        return sb.toString();
    }

    @Override
    public InnerResult login(User user) {
        List<User> users = mallUserDao.getUsers(user);
        if (null == users || 1 != users.size()) {
            return InnerResult.reject("用户名或密码错误");
        }
        User dbuser = users.get(0);

        //处理密码
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            String pwd = FACTOR.value + dbuser.getSalt() + user.getPwd();
            byte[] pwdBytes = digest.digest(pwd.getBytes(StandardCharsets.UTF_8));
            String hashPwd = getHashPwd(pwdBytes);
            return hashPwd.equals(dbuser.getPwd()) ? InnerResult.fulfill(new UserSignVO(0, dbuser.getNickname(), dbuser.getNickname())) : InnerResult.reject("用户名或密码错误");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return InnerResult.reject("登录失败");
    }

    @Override
    public InnerResult signup(User user) {
        List<User> dbusers = mallUserDao.getUsers(user);
        if (null != dbusers) {
            for (User u : dbusers) {
                if (u.getEmail().equalsIgnoreCase(user.getEmail())) {
                    return InnerResult.reject("邮箱已被占用");
                } else if (u.getNickname().equals(user.getNickname())) {
                    return InnerResult.reject("昵称已被占用");
                } else if (u.getPhone().equals(user.getPhone())) {
                    return InnerResult.reject("电话已被占用");
                }
            }
        }

        //处理密码，并插入数据库
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            String salt = Long.toHexString(RANDOM.nextLong());
            String pwd = FACTOR.value + salt + user.getPwd();
            byte[] pwdBytes = digest.digest(pwd.getBytes(StandardCharsets.UTF_8));
            String hashPwd = getHashPwd(pwdBytes);
            user.setPwd(hashPwd);
            user.setSalt(salt);
            int result = mallUserDao.signup(user);
            return 0 == result ? InnerResult.reject("注册失败") : InnerResult.fulfill(new UserSignVO(0, user.getNickname(), user.getNickname()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return InnerResult.reject("注册失败");
    }
}
